package com.example.android.models

import com.example.android.utils.websocket.MyWebSocket
import com.google.gson.GsonBuilder
import java.util.*

/**
 * @ClassName Message
 * @Author Ryan Kamanri
 * @Date 2022/6/12
 * @Description
 **/
open class Message(
    val id: Long,
    val sendUserId: Long,
    val receiveUserId: Long,
    val time: Date,
    val contentType: String,
    var content: Any
    ) {
    companion object {
        val Text = "text/plain"
        val Gif = "image/gif"
        val Jpg = "image/jpeg"
        val Png = "image/png"
    }
}

fun ArrayList<MyWebSocket.WebSocketMessage>.ToMessages(offset: Int = 0, length : Int = -1) : List<Message>{
    val result = arrayListOf<Message>()
    var _offset = offset
    val gson = GsonBuilder().setDateFormat("yyyy-MM-dd\'T\'HH:mm:ss").create()
    // length = -1 ===>  _offset < this.Count
    // length != -1 ===> _offset < this.Count && _offset - offset < length
    while (_offset < this.size && (_offset - offset < length || length == -1))
    {
        val message = gson.fromJson(this[_offset].Message as String, Message::class.java)
        if (message.contentType != Message.Text)
        {
            val bytesContent = (this[_offset + 1].Message as ByteArray)
            message.content = bytesContent
            result.add(message)
            _offset += 2
        }
        else
        {
            result.add(message)
            _offset++
        }

    }

    return result
}

fun Message.ToMessageView(viewType: MessageView.ViewType): MessageView {
    return MessageView(
        sendUserId,
        receiveUserId,
        time,
        contentType,
        content,
        viewType
    )

}